package com.guxingke.typecho4j.widget.handle.option;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.guxingke.typecho4j.Typecho4jException;
import com.guxingke.typecho4j.jfinal.model.Option;
import com.guxingke.typecho4j.route.DispatcherStrategy;
import com.guxingke.typecho4j.route.Route;
import com.guxingke.typecho4j.route.Routes;
import com.guxingke.typecho4j.util.SetOptUtils;
import com.guxingke.typecho4j.widget.WidgetHandle;
import com.guxingke.typecho4j.widget.layout.LayoutWidget;
import com.guxingke.typecho4j.widget.layout.back.option.ThemesOptionLayoutWidget;
import com.guxingke.typecho4j.widget.layout.front.SidebarLayoutWidget;
import com.guxingke.typecho4j.widget.provider.OptionBaseWidget;
import com.jfinal.core.Controller;

public class UpdateThemeOptionHandleWidget extends OptionBaseWidget implements
		WidgetHandle {

	private Set<String> options = new HashSet<String>();

	@Override
	public boolean init() {
		initLogger();
		options.add("ShowRecentPosts");
		options.add("ShowRecentComments");
		options.add("ShowCategory");
		options.add("ShowArchive");
		options.add("ShowOther");
		return true;
	}

	@Override
	public void configRoute(Routes routes) {
		routes.addRoute(new Route("updateThemeOption", this.getClass(),
				"/admin/options-themes",
				DispatcherStrategy.REDIRECT));
	}

	@Override
	public void handle(Controller controller) throws Typecho4jException {

		String logoUrl = controller.getPara("logoUrl");
		if (logoUrl != null) {
			setValue(new Option().set("name", "logoUrl").set(
					"value", logoUrl));
		}

		doUpdateHandle(controller);

		LayoutWidget.refreshLayout(ThemesOptionLayoutWidget.class);
		LayoutWidget.refreshLayout(SidebarLayoutWidget.class);
		constants.refreshThemeConfig();
	}

	private void doUpdateHandle(Controller controller) {
		if (controller.getParaValues("sidebarBlock[]") != null) {
			List<String> list = Arrays.asList(controller
					.getParaValues("sidebarBlock[]"));
			Set<String> results = new HashSet<String>();
			results.addAll(list);

			Set<String> temps = SetOptUtils.diff(results, options);
			for (String string : temps) {
				setValue(new Option().set("name", string).set(
						"value", "0"));
			}

			temps = SetOptUtils.intersect(results, options);
			for (String string : temps) {
				setValue(new Option().set("name", string).set(
						"value", "1"));
			}
		}
	}
}
